import json
import hashlib
import base64
import hmac
import os
import time
import requests
from urllib.parse import quote_plus


class Messenger:
    def __init__(self, token=os.getenv("DD_ACCESS_TOKEN"), secret=os.getenv("DD_SECRET")):
        self.timestamp = str(round(time.time() * 1000))
        self.URL = "https://oapi.dingtalk.com/robot/send"
        self.headers = {'Content-Type': 'application/json'}
        secret = secret
        secret_enc = secret.encode('utf-8')
        string_to_sign = '{}\n{}'.format(self.timestamp, secret)
        string_to_sign_enc = string_to_sign.encode('utf-8')
        hmac_code = hmac.new(secret_enc, string_to_sign_enc,
                             digestmod=hashlib.sha256).digest()
        self.sign = quote_plus(base64.b64encode(hmac_code))
        self.params = {'access_token': token, "sign": self.sign}

    def send_text(self, title, content):
        """
        发送文本
        @param content: str, 文本内容
        """
        data = {"msgtype": "link", "link":
                {"title": title,
                 "text": content,
                 "picUrl": "https://c-ssl.dtstatic.com/uploads/item/202006/27/20200627123212_fbkft.thumb.1000_0.jpg",
                 "messageUrl": "https://jwgl.lyu.edu.cn/"
                 }}
        self.params["timestamp"] = self.timestamp
        return requests.post(
            url=self.URL,
            data=json.dumps(data),
            params=self.params,
            headers=self.headers
        )


def main():
    m = Messenger(
        token="token",
        secret="secret"
    )
    m.send_text(title="教务系统可以正常稳定进入", content="点此链接进入教务系统")
